package com.wzdigit.wms.wms.service.task;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzdigit.wms.basic.client.Pager;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.request.task.UpdateTaskSchedulingRequest;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.client.response.task.TaskSchedulingReponse;
import com.wzdigit.wms.basic.domain.task.TaskScheduling;
import com.wzdigit.wms.basic.domain.task.TaskSchedulingDeal;
import com.wzdigit.wms.basic.enums.AsnTypeEnum;
import com.wzdigit.wms.basic.enums.GdnTypeEnum;
import com.wzdigit.wms.basic.enums.TransferTypeEnum;
import com.wzdigit.wms.basic.mapper.core.task.TaskSchedulingMapper;
import com.wzdigit.wms.basic.util.HttpSessionUtil;
import com.wzdigit.wms.basic.util.enums.DocModuleEnum;
import com.wzdigit.wms.wms.service.core.InvokeMethodService;
import com.wzdigit.wms.wms.service.core.task.TaskSchedulingCodeService;
import com.wzdigit.wms.wms.service.core.task.TaskSchedulingDealCodeService;
import com.wzdigit.wms.wms.task.DefaultSchedulingConfigurer;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 调度任务管理
 * 
 * @author Administrator
 *
 */
@Service
@Slf4j
public class TaskScheduleService {
	
	@Autowired
	private TaskSchedulingMapper taskSchedulingMapper;
	
	@Autowired
	private InvokeMethodService invokeMethodService;
	
	@Autowired
	private TaskSchedulingCodeService taskSchedulingCodeService;
	
	@Autowired
	private TaskSchedulingDealCodeService taskSchedulingDealCodeService;

	@Autowired
	private DefaultSchedulingConfigurer defaultSchedulingConfigurer;
	
	@Value("${schedule.common.switch}")
    private Boolean scheduleCommonSwitch;

	/**
	 * 初始化系统配置的调度任务
	 * @throws Exception 
	 */
	@PostConstruct
	private void initialize() throws Exception {
		if(scheduleCommonSwitch) {
			new Thread() {
				public void run() {
					try {
						// 等待调度器初始化
						while (!defaultSchedulingConfigurer.inited()) {
							log.info("等待调度器初始化...");
							Thread.sleep(3000);
						}
						
						// 遍历所有调度任务（启用）
						List<TaskScheduling> taskSchedulings = taskSchedulingCodeService.getUsingAll();
						for (TaskScheduling taskScheduling : taskSchedulings) {
							log.info("【" + taskScheduling.getName() + "】初始化...");
							TaskSchedulingDeal deal = taskSchedulingDealCodeService.getOneByTaskSchedulingId(taskScheduling.getTaskSchedulingId());
							if(deal != null) {
								invokeMethodService.invokeMethod(deal.getDealClass(), deal.getDealMethod(), deal.getDealParam(), taskScheduling);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.start();
		} else {
			log.info("不初始化调度任务");
		}
	}
	
	public static void main(String[] args) {
		System.err.println(DocModuleEnum.ASN);
	}
	
	/**
	 * 查询所有的调度任务
	 * @param pager
	 * @return
	 */
	public PagerInfo<List<TaskSchedulingReponse>> searchTaskSchedule(Pager<?> pager) {
		Page<?> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
		PagerInfo<List<TaskSchedulingReponse>> pagerInfo = new PagerInfo<>();

		List<TaskSchedulingReponse> list = taskSchedulingMapper.selectAll();
		list.stream().forEach(t -> {
			switch (DocModuleEnum.getEnumByCode(t.getDocGroup())) {
			case ASN:
				t.setDocTypeMap(AsnTypeEnum.getEnumByDescription());
				break;
			case GDN:
				t.setDocTypeMap(GdnTypeEnum.getEnumByDescription());
				break;
			case TRANSFER:
				t.setDocTypeMap(TransferTypeEnum.getEnumByDescription());
				break;
			default:
				break;
			}
		});
		pagerInfo.setTotalCount(page.getTotal());
		pagerInfo.setItems(list);
		return pagerInfo;
	}
	
	/**
	 * 修改调度任务
	 * @param dto
	 * @param servletRequest
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public Result<?> updateTaskSchedule(UpdateTaskSchedulingRequest dto, 
			HttpServletRequest servletRequest) throws Exception {
		TaskScheduling taskScheduling = taskSchedulingMapper.selectById(dto.getTaskSchedulingId());
		
		BeanUtil.copy(dto, taskScheduling);
		taskScheduling.setModifyTime(new Date());
		taskScheduling.setModifyUser(HttpSessionUtil.getLoginName(servletRequest));
		taskSchedulingMapper.updateById(taskScheduling);
		
		// 取消当前调度任务
		defaultSchedulingConfigurer.cancelTriggerTask(taskScheduling.getTaskSchedulingId(), taskScheduling.getName());
		
		// 重置当前调度任务
		TaskSchedulingDeal deal = taskSchedulingDealCodeService.getOneByTaskSchedulingId(taskScheduling.getTaskSchedulingId());
		if(deal != null) {
			invokeMethodService.invokeMethod(deal.getDealClass(), deal.getDealMethod(), deal.getDealParam(), taskScheduling);
		}
        return new Result<>();
    }
}